<template>
    <div class="record-container">
        <div class="left">
            <TitleTips title="日常养护合同"></TitleTips>            
            <div v-if="contractList.length > 0" v-loading="schemeLoading" class="list">
                <el-tree ref="tree" default-expand-all :data="contractList" :props="defaultProps" node-key="id" :default-expanded-keys="defaultExpandedKeys" highlight-current @node-click="handleNodeDetail">
                    <div slot-scope="{ node, data }" class="custom-tree-node">
                        <span style="display: flex;align-items: center;">
                            <IconSvg v-if="!node.isLeaf && node.expanded" icon-class="file-open" class="file-icon"></IconSvg>
                            <IconSvg v-if="!node.isLeaf && !node.expanded" icon-class="file" class="file-icon"></IconSvg>                        
                            <IconSvg v-if="node.isLeaf" icon-class="catalogue" class="catalogue-icon"></IconSvg>

                            <span class="node-label g-line-1" :class="{ 'parent-node': !node.isLeaf }">
                                {{ data.projectName || data.highwayName }}
                            </span>
                        </span>

                        <el-dropdown v-if="!node.isLeaf" trigger="click">                            
                            <div style="padding: 2px 4px;" @click.stop>
                                <i class="el-icon-more more-icon" style="transform: rotate(90deg); cursor: pointer;"></i>
                            </div>
                            <el-dropdown-menu slot="dropdown" class="contract-dropdown">
                                <div>合同编号：{{ data.code }}</div>
                                <div>工期：{{ data.startDate }}~{{ data.endDate }}</div>
                                <div class="color-blue" style="cursor: pointer;" @click="handleToContaractDetail(data.id)"><i class="el-icon-document" style="font-size: 15px;"></i> 查看合同</div>
                            </el-dropdown-menu>
                        </el-dropdown>                        
                    </div>
                </el-tree>
            </div>
            <div v-else class="no-data">
                <IconSvg icon-class="no-data2" class="icon"></IconSvg>
                <span>暂无数据，<i class="button" @click="handleAddContract">前往配置合同</i></span>
            </div>
        </div>
        <BasePage style="flex: 1;">
            <TitleTips slot="title" title="养护记录"></TitleTips>
            <el-form slot="form" :inline="true" size="medium" @submit.native.prevent>
                <el-form-item label="养护记录编号">
                    <el-input v-model="form.recordCode" placeholder="请输入" style="width: 160px;" clearable></el-input>
                </el-form-item>
                <el-form-item label="养护日期">
                    <el-date-picker
                        v-model="form.date"
                        type="daterange"
                        style="width: 230px;"
                        value-format="yyyy-MM-dd"
                        :editable="false"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    />
                </el-form-item>
                <el-form-item label="类型">
                    <el-select v-model="form.type" clearable placeholder="请选择" style="width: 160px;">
                        <el-option v-for="item in recordTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="计量状态" label-width="100px">
                    <el-select v-model="form.msStatus" clearable placeholder="请选择" style="width: 160px;">
                        <el-option v-for="item in metrologicalStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <BaseButton v-permission="{ btnCode: 'dlyh_c84_d407_2' }" :disabled="contractList.length === 0" @click="handleFilter">查询</BaseButton>
                    <BaseButton v-permission="{ btnCode: 'dlyh_c84_d407_2' }" type="second" :disabled="contractList.length === 0" @click="resetConditions()">重置</BaseButton>
                </el-form-item>
            </el-form>

            <div slot="button">
                <BaseButton v-permission="{ btnCode: 'dlyh_c84_d408_2' }" :disabled="contractList.length === 0" @click="handleAdd">新增养护记录</BaseButton>
                <BaseButton v-permission="{ btnCode: 'dlyh_c84_d409_2' }" :disabled="contractList.length === 0 || list.length === 0" :loading="visaLoading" type="second" @click="handleExport(1)">导出签证单</BaseButton>
                <BaseButton v-permission="{ btnCode: 'dlyh_c84_d410_2' }" :disabled="contractList.length === 0 || list.length === 0" :loading="cardLoading" type="second" @click="handleExport(2)">导出档案卡</BaseButton>
            </div>

            <!--数据列表区-->
            <BaseTable
                slot="table"
                ref="table"
                v-loading="listLoading"
                :columns="columns"
                :data="list"
                row-key="id"
                height="calc(100% - 73px)"
                highlight-current-row
                @sort-change="handleSortChange"
            >
                <template #code="{ scope: { row } }">
                    <span v-if="buttonsRights.has('dlyh_c84_d411_2')" class="color-blue" style="cursor: pointer;" @click="handleDetail(row.id)">{{ row.recordCode }}</span>
                    <span v-else>{{ row.recordCode }}</span>
                </template>
                <template #type="{ scope: { row } }">
                    <span>{{ row.type | value2Name(recordTypeOptions, 'value', 'label') }}</span>
                </template>
                <template #status="{ scope: { row } }">
                    <span class="dot" :style="`background-color: ${metrologicalStatusColor[row.msStatus]};`"></span>  
                    <span>{{ row.msStatusName }}</span>
                </template>
                <template #handle="{ scope: { row } }">
                    <BaseButton type="text" @click="handleDetail(row.id)">查看</BaseButton>
                    <BaseButton v-show="row.msStatus !==2 && row.msStatus !==3" v-permission="{ btnCode: 'dlyh_c84_d412_2' }" type="text" @click="handleEdit(row.id)">编辑</BaseButton>
                    <BaseButton v-show="row.msStatus !==2 && row.msStatus !==3" v-permission="{ btnCode: 'dlyh_c84_d413_2' }" type="text" color="danger" @click="handleDelete(row.id)">删除</BaseButton>
                </template>
            </BaseTable>
            <!--分页组件-->
            <Pagination
                slot="pagination"
                :current-page.sync="page.pageNo"
                :page-size.sync="page.pageSize"
                :total="page.total"
                @current-change="getList"
                @size-change="getList"
            />
        </BasePage>
    </div>
</template>

<script>
import BasePage from '@/layouts/BasePage'
import { MaintenanceRecordManagementModel, MsMaintrecordModel } from '@/models'
import { MaintenanceRecordManagementApi } from '@/api'
import reconfirm from '@/utils/reconfirm'
import { RecordTypeOptions, MetrologicalStatusOptions, MetrologicalStatusColor } from '@/views/maintenance-decision/constants'
import KeepAliveHandler from '@/mixins/keepAliveHandler'
import { value2Name } from '@/filters'
import downLoad from '@/utils/blob-download'

const ExportMap = {
    1: {
        api: 'exportVisaVoucherPath',
        loading: 'visaLoading'
    },
    2: {
        api: 'exportArchiveCardPath',
        loading: 'cardLoading'
    }
}
export default {
    name: 'MaintenanceRecordManagementList',
    components: {
        BasePage
    },
    filters: {
        value2Name
    },
    mixins: [
        KeepAliveHandler({
            defaultCondition: {
                recordCode: '',
                date: [],
                type: '',
                msStatus: '',
                sortFields: [],
                contractId: '',
                highwayCode: ''
            },
            conditionObjKey: 'form',
            tableRef: 'table'
        })
    ],
    data() {
        return {
            visaLoading: false,
            cardLoading: false,
            defaultProps: {
                children: 'maintScopeList'
            },
            defaultExpandedKeys: [],
            recordTypeOptions: RecordTypeOptions,
            metrologicalStatusOptions: MetrologicalStatusOptions,
            metrologicalStatusColor: MetrologicalStatusColor,
            chapterCode: '',
            model: new MaintenanceRecordManagementModel(),
            msMaintrecordModel: new MsMaintrecordModel(),
            contractList: [],
            listLoading: false,
            schemeLoading: true,
            form: {
                recordCode: '',
                date: [],
                type: '',
                msStatus: '',
                sortFields: [],
                contractId: '',
                highwayCode: ''
            },
            list: [],
            page: {
                pageNo: 1,
                pageSize: 10,
                total: 0
            },
            columns: Object.freeze([
                {
                    slot: 'code',
                    attrs: {
                        prop: 'recordCode',
                        label: '养护记录编号',
                        width: '146',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'maintDate',
                        label: '养护日期',
                        width: '120',
                        sortable: 'custom',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'type',
                    attrs: {
                        prop: 'type',
                        label: '类型',
                        width: '100',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'constructionUnitName',
                        label: '施工单位',
                        'min-width': '170',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'managementUnitName',
                        label: '现场管理',
                        'min-width': '140',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'workContent',
                        label: '工作内容',
                        'min-width': '160',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'status',
                    attrs: {
                        prop: 'msStatusName',
                        label: '计量状态',
                        width: '130',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'operatorName',
                        label: '更新人',
                        'show-overflow-tooltip': true,
                        width: '110',
                    }
                },
                {
                    attrs: {
                        prop: 'updateTime',
                        label: '更新时间',
                        sortable: 'custom',
                        'show-overflow-tooltip': true,
                        width: '170',
                    }
                },
                {
                    slot: 'handle',
                    attrs: {
                        label: '操作',
                        width: '160',
                        fixed: 'right'
                    }
                },
            ]),
            contractInfo: {} // 用于新增记录时携带的固定参数
        }
    },
    computed: {
        buttonsRights() {
            return this.$store.getters['user/pageRights']
        }
    },
    async created() {
        await this.getContractTreeList()
        if (this.contractList.length > 0) {
            this.initList()
        }
    }, 
    methods: {
        handleExport(type) {
            this[ExportMap[type].loading] = true
            const path = MaintenanceRecordManagementApi[ExportMap[type].api]
            const [startDate = null, endDate = null] = this.form.date || []
            const params = {
                ...this.form,
                startDate,
                endDate
            }
            downLoad(path, params, '', 'Excel', () => {
                this[ExportMap[type].loading] = false
            })
        },
        handleNodeDetail(data, node) {
            if (node.isLeaf) {
                this.form.contractId = node.parent.data.id
                this.form.highwayCode = data.highwayCode
                // 用于重置参数
                this.defaultCondition = {
                    contractId: this.form.contractId,
                    highwayCode: this.form.highwayCode
                }

                this.contractInfo = {
                    contractId: node.parent.data.id,
                    highwayCode: data.highwayCode,
                    highwayName: data.highwayName,
                    startStakeNo: data.startStakeNo,
                    endStakeNo: data.endStakeNo,
                    constructionUnitId: node.parent.data.contractorId,
                    constructionUnitName: node.parent.data.contractorName,
                    projectName: node.parent.data.projectName,
                }
                this.getList()
            }
        },
        // 排序
        handleSortChange({ column, prop, order }) {  
            if (prop === 'updateTime') {
                if (order === 'ascending') {  
                    this.form.sortFields = [
                        {
                            sortFieldName: 'update_time',
                            sortType: 'asc'
                        }
                    ]
                } else if (order === 'descending') {
                    this.form.sortFields = [
                        {
                            sortFieldName: 'update_time',
                            sortType: 'desc'
                        }
                    ]
                } else {
                    this.form.sortFields = []
                }
            }
            if (prop === 'maintDate') {
                if (order === 'ascending') {  
                    this.form.sortFields = [
                        {
                            sortFieldName: 'maint_date',
                            sortType: 'asc'
                        }
                    ]
                } else if (order === 'descending') {
                    this.form.sortFields = [
                        {
                            sortFieldName: 'maint_date',
                            sortType: 'desc'
                        }
                    ]
                } else {
                    this.form.sortFields = []
                }
            }
            this.getList()
        },
        initList() {
            const active = this.contractList[0].maintScopeList[0] || {}
            this.form.contractId = this.contractList[0].id
            this.form.highwayCode = active.highwayCode

            this.contractInfo = {
                contractId: this.contractList[0].id,
                highwayCode: active.highwayCode,
                highwayName: active.highwayName,
                startStakeNo: active.startStakeNo,
                endStakeNo: active.endStakeNo,
                constructionUnitId: this.contractList[0].contractorId,
                constructionUnitName: this.contractList[0].contractorName,
                projectName: this.contractList[0].projectName,
            }
            // 用于重置参数
            this.defaultCondition = {
                contractId: this.form.contractId,
                highwayCode: this.form.highwayCode
            }
            
            this.$nextTick(() => {
                // 默认展开第一个，并选中第一个子项
                this.defaultExpandedKeys = [this.contractList[0].id]
                this.$refs.tree.setCurrentKey(active.id)
            })
            this.getList()
        },
        // 养护单价列表
        getList() {
            this.listLoading = true
            const [startDate = null, endDate = null] = this.form.date || []
            this.model
                .getList({...this.page, ...this.form, startDate, endDate})
                .then(res => {
                    this.list = res.list || []
                    this.page.total = res.totalCount
                    this.totalAmount = res.totalAmount
                })
                .finally(() => {
                    this.listLoading = false
                })
        },
        // 左边的合同列表
        getContractTreeList() {
            this.schemeLoading = true
            return this.msMaintrecordModel
                .contractTreeList()
                .then(res => {
                    this.contractList = res || []
                })
                .finally(() => {
                    this.schemeLoading = false
                })
        },
        handleToContaractDetail(id) {
            this.$router.push({
                name: 'ContractDetail',
                query: { id }
            })
        },
        // 查询
        handleFilter() {
            this.page.pageNo = 1
            this.getList()
        },
        handleAddContract() {
            this.$router.push({ name: 'ContractAdd'})
        },
        handleImport() {
            this.$refs['importDialog'].open({
                contractId: this.id,
            })
        },
        checkDeleteList() {
            this.$refs['deleteListDialog'].open({
                contractId: this.id,
            })
        },
        checkoutLog() {
            this.$refs['logDialog'].open()
        },
        handleAdd() {
            this.$router.push({
                name: 'MaintenanceRecordManagementAdd',
                query: {
                    ...this.contractInfo,
                    type: 'add'
                }
            })
        },
        handleEdit(id) {
            this.$router.push({
                name: 'MaintenanceRecordManagementEdit',
                query: { id, type: 'edit', contractId: this.contractInfo.contractId }
            })
        },
        handleDetail(id) {
            this.$router.push({
                name: 'MaintenanceRecordManagementDetail',
                query: { id }
            })
        },
        handleDelete(id) {
            reconfirm({
                text: '确定删除该记录？</br>删除后无法恢复，请谨慎操作！',
                type: 'error',
                dangerouslyUseHTMLString: true,
                callback: () => {
                    return this.model.delete({ id }).then(() => {
                        this.getList()
                        this.$message.success('删除成功!')
                    })
                }
            })
        },
    },

}
</script>
<style lang="scss" scoped>
.contract-dropdown {
    padding: 8px 16px;
    font-size: 14px;
    line-height: 1.8;
}
.record-container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    .no-data {
        color: #9090A0;
        font-size: 14px;
        text-align: center;
        padding: 140px 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        .icon {
            font-size: 66px;
            padding-bottom: 12px;
            color: #c2c2c2;
        }
        .button {
            color: #0162FF;
            font-style: normal;
            cursor: pointer;
        }
    }
    .left {
        width: 330px;
        height: 100%;
        margin-right: 16px;
        flex-shrink: 0;
        border: 1px solid #f0f4f7;
        box-shadow: 0px 0px 4px 0px rgba(131, 145, 178, 0.14);
        padding: 24px 16px;
        .list {
            height: calc(100% - 38px);
            overflow-y: auto;
        }
    }
    .title-item {
        margin-left: 32px;
    }

    /* 替换默认展开收起图片 */
    ::v-deep {

        // 树结构重置前面图标
        .el-tree-node__expand-icon {
            width: 16px;
            height: 16px;
            margin-right: 4px;
            background: url("~@/assets/images/zhankai.png") no-repeat;
            background-size: 100% 100%;
            margin-left: 8px;
            flex-shrink: 0;
        }
        .el-tree-node__expand-icon.is-leaf {
            visibility: hidden;
        }
        .el-icon-caret-right:before {
            content: '';
        }
        
        .el-tree-node__expand-icon.expanded {
            transform: none;
            background: url("~@/assets/images/shouqi.png") no-repeat;
            background-size: 100% 100%;
            margin-right: 4px;
            flex-shrink: 0;
        }
        .el-tree-node__content {
            height: auto;
            padding-right: 8px;
        }
        .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content,
        .el-tree-node__content:hover {
            background-color: rgba(0, 98, 255, 0.06);
        }

        .el-tree-node__content:hover .more-icon {
            display: block;
        }
        
    }
    .icon-flex {
        display: flex;
        align-items: center;

        .file-icon {
            font-size: 22px;
            margin-right: 4px;
            flex-shrink: 0;
        }
        .catalogue-icon {
            font-size: 18px;
            margin-right: 4px;
            flex-shrink: 0;
        }
    }
    .custom-tree-node {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        padding: 8px 0;
        
        .file-icon {
            font-size: 22px;
            margin-right: 4px;
        }
        .catalogue-icon {
            font-size: 18px;
            margin-right: 4px;
        }
        .node-label {
            max-width: 210px;
            font-size: 14px;
        }
        .more-icon {
            display: none;
        }
    }
}
.dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    display: inline-block;
    margin-right: 4px;
    margin-bottom: 1px;
}
</style>
